package com.wandian.setting.mvvm.usersetting;

import android.app.Activity;
import android.app.Application;
import android.util.Log;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.bean.BaseBean;
import com.mylib.libcore.bean.OSSDataBean;
import com.mylib.libcore.bean.UserInfoBean;
import com.mylib.libcore.mvvm.BaseViewModel;
import com.mylib.libcore.network.rx.RxResultHelper;
import com.mylib.libcore.utils.FileUtil;
import com.mylib.libcore.utils.GlideUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.OssManager;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.crc.AESUtils;
import com.mylib.widget.RoundImageView;
import com.wandian.setting.bean.CZDataBean;
import com.wandian.setting.data.BaseAppApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.mylib.libcore.config.NetConfig.BASE_SUCCESS_CODE;


/**
 * @author Administrator
 * @date 2019/12/18-16:11
 * @description
 **/
public class UserSettingViewModel extends BaseViewModel{

    private BaseAppApi baseAppApi;
    public MutableLiveData<UserInfoBean> userBean = new MutableLiveData<>();
    public MutableLiveData<OSSDataBean> oosBean = new MutableLiveData<>();
    public UserSettingViewModel(@NonNull Application application) {
        super(application);
        baseAppApi = RetrofitUtil.getAppRetrofit().create(BaseAppApi.class);
    }

    public void getUserInfo(){
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.getUserInfo(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        Log.d("getUserInfo",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            try {
                                if(!UIUtils.isEmpty(bean.getData())){
                                    Log.d("crc_rc4key_getVersion", AESUtils.getInstance().decrypt(bean.getData()));
                                    UserInfoBean userInfoBean = JsonUtil.parseJsonToBean(AESUtils.getInstance().decrypt(bean.getData()),UserInfoBean.class);
                                    if(!UIUtils.isEmpty(userInfoBean)){
                                        userBean.setValue(userInfoBean);
                                        AppContext.getInstance().getAppPreferencesHelper().setUserInfoBean(userInfoBean);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void modifySex(String sex){
        showDialog();
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("sex", sex);
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.upSex(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("upSex",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            ToastUtil.show("修改成功");
                        }else {
                            ToastUtil.show("数据异常");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        Log.d("upSex",   JsonUtil.toJson(e));
                        if(!UIUtils.isEmpty(e.getMessage())){
                            ToastUtil.show(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void modifyHead(Activity activity, RoundedImageView ivHead, String headUrl){
        showDialog();
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("headPic", headUrl);
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.upHeadPic(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("upHeadPic",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            GlideUtil.intoHeadImg(activity,headUrl,ivHead);
                        }else {
                            ToastUtil.show("网络错误");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        Log.d("upHeadPic",   JsonUtil.toJson(e));
                        if(!UIUtils.isEmpty(e.getMessage())){
                            ToastUtil.show(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //获取oosToken
    public void getOOSToken(){
        showDialog();
        JsonObject jsonObject = new JsonObject();
        HashMap<String, String> hashMap = new HashMap<>();
        jsonObject.addProperty("wdk", AESUtils.getInstance().encrypt(hashMap));
        RxResultHelper.getHttpObservable(getLifecycleProvider(), baseAppApi.getOOSToken(jsonObject))
                .subscribe(new Observer<BaseBean<Object>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }
                    @Override
                    public void onNext(BaseBean<Object> bean) {
                        dismissDialog();
                        Log.d("getOOSToken",   JsonUtil.toJson(bean));
                        if(!UIUtils.isEmpty(bean) && bean.getCode()==BASE_SUCCESS_CODE){
                            String json = AESUtils.getInstance().decrypt(bean.getData())+"";
                            Log.d("getOOSToken",   json);
                            if(!UIUtils.isEmpty(json) && json.length()>4){
                                OSSDataBean ossDataBean =JsonUtil.parseJsonToBean(json,OSSDataBean.class);
                                oosBean.setValue(ossDataBean);
                            }else {
                                ToastUtil.show("网络异常请重试");
                                oosBean.setValue(null);
                            }
                        }else {
                            oosBean.setValue(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        oosBean.setValue(null);
                        dismissDialog();
                        Log.d("getOOSToken",   JsonUtil.toJson(e));
                        if(!UIUtils.isEmpty(e.getMessage())){
                            ToastUtil.show(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    // 上传图片
    public void upLoadImg(Activity activity, RoundedImageView imageView, OSSDataBean ossDataBean , String imgPath){
        showDialog();
        try {
            OssManager.getInstance().upload(activity, ossDataBean,imgPath,OssManager.getHeadPicPath(imgPath), 0, new OssManager.OnUploadListener() {

                        @Override
                        public void onProgress(int position, long currentSize, long totalSize) {
                        }

                        @Override
                        public void onSuccess(int position, String uploadPath, String imageUrl) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    modifyHead(activity,imageView,imageUrl);
                                }
                            });

                            FileUtil.deleteFileByPath(imgPath);

                        }

                        @Override
                        public void onFailure(int position) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    ToastUtil.show("图片上传失败");
                                }
                            });
                        }
                    }
            );
        } catch (Exception e) {
            dismissDialog();
            e.printStackTrace();
        }
    }
}
